package net.fenghaitao.utils;

import net.fenghaitao.domain.ExcelVerifyHandlerResult;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;

/**
 * @author ：HuangXiong
 * @date ：Created in 2021/1/7 10:19
 * @description： 通用验证处理方法 工具类，符合JSR303验证规范，内部采用Hibernate Validator实现
 * @modified By：
 * @version:
 */
public class ValidationUtil {

    /**
     * 开启快速结束模式 failFast (true)
     */
    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验对象
     *
     * @param t      bean
     * @param groups 校验组
     * @return ValidResult
     */
    public static <T> ExcelVerifyHandlerResult validateBean(T t, Class<?>... groups) {
        ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult();

        Set<ConstraintViolation<T>> violationSet = validator.validate(t, groups);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {

                result.addError(
                        violation.getPropertyPath().toString(),
                        violation.getMessage(),
                        Objects.equals(violation.getMessage(), violation.getMessageTemplate())
                );
            }
        }
        return result;
    }

    /**
     * 校验bean的某一个属性
     *
     * @param obj          bean
     * @param propertyName 属性名称
     * @return ValidResult
     */
    public static <T> ExcelVerifyHandlerResult validateProperty(T obj, String propertyName) {
        ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult();
        Set<ConstraintViolation<T>> violationSet = validator.validateProperty(obj, propertyName);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(propertyName, violation.getMessage());
            }
        }
        return result;
    }





}
